package com.yuanduo_app.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.fondesa.recyclerviewdivider.manager.inset.DefaultInsetManager;
import com.xujl.fastlib.utils.NumberUtils;
import com.xujl.fastlib.utils.ResUtils;
import com.xujl.fastlib.utils.StringUtils;
import com.xujl.fastlib.utils.ToastUtils;

import com.yuanduo_app.MainApplication;
import com.yuanduo_app.R;

import java.lang.reflect.Method;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import androidx.recyclerview.widget.RecyclerView;

public class ViewHelper {

    public static String getText (TextView tv) {
        return tv.getText().toString().trim();
    }

    public static void addItemHorizontalDecoration (RecyclerView rv) {
        addItemHorizontalDecoration(rv, 2);
    }

    public static void addItemHorizontalDecoration (RecyclerView rv, int size) {
        RecyclerViewDivider.with(rv.getContext())
                .insetManager(new DefaultInsetManager())
                .hideLastDivider()
                .size(size)
                .color(ResUtils.getColor(R.color.line_divider))
                .build().addTo(rv);
    }

    public static void addItemVerticalDecoration (RecyclerView rv, int size) {
        addItemVerticalDecoration(rv, size, R.color.line_divider);
    }

    public static void addItemVerticalDecoration (RecyclerView rv, int size, int color) {
        RecyclerViewDivider.with(rv.getContext())
                .insetManager(new DefaultInsetManager())
                .hideLastDivider()
                .size(size)
                .color(ResUtils.getColor(color))
                .build().addTo(rv);
    }

    public static void addItemVerticalDecorationAll (RecyclerView rv, int size, int color) {
        RecyclerViewDivider.with(rv.getContext())
                .insetManager(new DefaultInsetManager())
                .size(size)
                .color(ResUtils.getColor(color))
                .build().addTo(rv);
    }

    public static void addItemHorizontalVerticalDecoration (RecyclerView rv, int size, int color) {
        RecyclerViewDivider.with(rv.getContext())
                .insetManager(new DefaultInsetManager())
                .size(dip2px(rv.getContext(), size))
                .color(ResUtils.getColor(color))
                .build().addTo(rv);
    }

    public static int dip2px (Context context, float dipValue) {
        return (int) (dipValue * (getScreenDensity(context) / 160f) + 0.5f);
    }

    public static int px2dip (Context context, float pxValue) {
        return (int) ((pxValue * 160) / getScreenDensity(context));
    }

    public static float sp2px (Context context, float sp) {
        return sp * getScreenScaledDensity(context);
    }

    public static float px2sp (Context context, float px) {
        return px / getScreenScaledDensity(context) + 0.5f;
    }

    @SuppressWarnings("deprecation")
    public static int getScreenDensity (Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();

        return dm.densityDpi;
    }

    /*** get Screen Density * @param context * @return */
    @SuppressWarnings("deprecation")
    public static float getScreenScaledDensity (Context context) {
        return context.getResources().getDisplayMetrics().scaledDensity;
    }

    /**
     * 获取屏幕尺寸
     *
     * @param context
     * @return
     */
    public static DisplayMetrics getScreenSize (Context context) {
        Resources resources = context.getResources();
        return resources.getDisplayMetrics();
    }

    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param phoneNum 电话号码
     */
    public static void callPhone (Context context, String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.toast("拨号失败");
        }
    }

    /**
     * 强制关闭键盘
     *
     * @param view
     */
    public static void closeKeyBoard (View view) {
        InputMethodManager imm = (InputMethodManager) MainApplication.getApplication()
                .getSystemService(MainApplication.getApplication().INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }


    public static String getDiscount (String discount) {
        if (StringUtils.isEmpty(discount)) {
            return "0";
        }
        return NumberUtils.bigDecimalOf(discount).multiply(NumberUtils.bigDecimalOf(10)).doubleValue() + "";
    }


    public static int stringDptoPx (String dp) {
        return ViewHelper.dip2px(MainApplication.getApplication(), NumberUtils.floatOf(dp));
    }

    /**
     * 匹配文字变色
     *
     * @param color
     * @param text
     * @param keyword
     * @return
     */
    public static SpannableString matcherSearchText (int color, String text, String keyword) {
        if (StringUtils.isEmpty(text) || StringUtils.isEmpty(text)) {
            return new SpannableString(text);
        }
        SpannableString ss = new SpannableString(text);
        Pattern pattern = Pattern.compile(keyword);
        Matcher matcher = pattern.matcher(ss);
        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            ss.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return ss;
    }

    public static void toSelfSetting (Context context) {
        Intent mIntent = new Intent();
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            mIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            mIntent.setAction(Intent.ACTION_VIEW);
            mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
            mIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        context.startActivity(mIntent);
    }


    /**
     * 获取虚拟按键的高度
     */
    public static int getNavigationBarHeight (Context context) {
        int result = 0;
        if (hasNavBar(context)) {
            Resources res = context.getResources();
            int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = res.getDimensionPixelSize(resourceId);
            }
        }
        return result;
    }

    /**
     * 检查是否存在虚拟按键栏
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    private static boolean hasNavBar (Context context) {
        Resources res = context.getResources();
        int resourceId = res.getIdentifier("config_showNavigationBar", "bool", "android");
        if (resourceId != 0) {
            boolean hasNav = res.getBoolean(resourceId);
            String sNavBarOverride = getNavBarOverride();
            if ("1".equals(sNavBarOverride)) {
                hasNav = false;
            } else if ("0".equals(sNavBarOverride)) {
                hasNav = true;
            }
            return hasNav;
        } else {
            return !ViewConfiguration.get(context).hasPermanentMenuKey();
        }

    }

    /**
     * 判断虚拟按键栏是否重写
     */
    private static String getNavBarOverride () {
        String sNavBarOverride = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                Class c = Class.forName("android.os.SystemProperties");
                Method m = c.getDeclaredMethod("get", String.class);
                m.setAccessible(true);
                sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sNavBarOverride;
    }

}
